<?php

namespace App\Http\Controllers\Admin\Personnel;

use App\Http\Controllers\Controller;
use App\Imports\RouteImport;
use App\Models\AdminAuthModel;
use App\Models\AdminModel;
use App\Models\AdminRoleModel;
use App\Models\StaffModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class Auth extends Controller
{

    public function buildTree(array $data, $parentId = 0) {
        $tree = [];
        foreach ($data as $element) {
            if ($element['pid'] == $parentId) {
                $children = $this->buildTree($data, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $tree[] = $element;
            }
        }
        return $tree;
    }

    public function route(Request $request){
        $auth = $request->get('auth');

        $admin = AdminModel::find($auth->id);
        if(!$admin) {
            return $this->error('用户不存在');
        }

        $staff = $admin->staff;
        if(!$staff) {
            return $this->error('关联员工错误');
        }

        $role = AdminRoleModel::find($staff->role_id);
        if(!$role) {
            return $this->error('员工角色错误');
        }
        $query = AdminAuthModel::query();

        if($role->auth != '*'){
            $ids = json_decode($role->auth);
            $query = $query->whereIn('id', $ids);
        }

        $route = $query->get()->toArray();
        foreach($route as $k => $item) {
            $route[$k]['noCache'] = boolval($item['noCache']);
        }

        $tree = $this->buildTree($route);
        
        return $this->success($tree);
    }

    public function route_app(Request $request){
        $auth = $request->get('auth');
        $role = AdminRoleModel::find($auth->role_id);

        $query = AdminAuthModel::query()->where('platform', AdminAuthModel::APP_PLATFORM);
        if($role->auth == '*') {
            $route = $query->get()->toArray();
        } else {
            $ids = json_decode($role->auth);
            $route = $query->whereIn('id', $ids)->get()->toArray();
        }

        $tree = $this->buildTree($route);
        
        return $this->success($tree);
    }

    public function menu_old(Request $request) {
        $auth = $request->get('auth');

        $admin = AdminModel::find($auth->id);

        $role = AdminRoleModel::find($admin->staff?->role_id);
        if(!$role) {
            return $this->success([]);
        }

        $query = AdminAuthModel::query()
            ->where('platform', AdminAuthModel::ADMIN_PLATFORM)
            ->select('id', 'icon', 'title', 'path', 'pid', 'type', 'name', 'noCache')
            ->whereIn('type', [1,2]);
        if($role->auth != '*') {
            $ids = json_decode($role->auth);
            $query = $query->whereIn('id', $ids);
        }
        $route = $query->get()->toArray();
        foreach($route as $k => $item) {
            $route[$k]['noCache'] = boolval($item['noCache']);
        }
            
        $tree = $this->buildTree($route);
        
        return $this->success($tree);
    }

    public function menu(Request $request) {
        $auth = $request->get('auth');

        $admin = AdminModel::find($auth->id);

        $query = AdminAuthModel::query()
            ->where('platform', AdminAuthModel::ADMIN_PLATFORM)
            ->select('id', 'icon', 'title', 'path', 'pid', 'type', 'name', 'noCache')
            ->whereIn('type', [1,2]);
        if($admin->auth == '*') {
            $route = $query->get()->toArray();
        } else {
            $ids = $admin->auth ? json_decode($admin->auth) : [];
            $route = $query->whereIn('id', $ids)->get()->toArray();
        }
            
        $tree = $this->buildTree($route);
        
        return $this->success($tree);
    }

    public function add(Request $request){
        $params = $request->all();
        $validator = Validator::make($params, [
            'type' => 'required|in:1,2,3',
            'title' => 'required',
            'platform' => 'required|in:1,2'
        ], [
            'type.required' => '请选择菜单类型',
            'type.in' => '菜单类型错误',
            'title.required' => '请填写标题',
            'platform.required' => '请选择权限平台',
            'platform.in' => '权限平台错误',
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        $method = strtolower($params['method'] ?? '');
        if(!in_array($method, AdminAuthModel::METHOD)) {
            return $this->error('请求方法错误');
        }

        $pid = intval($params['pid'] ?? 0);
        if($pid) {
            $parent = AdminAuthModel::find($pid);
            if(!$parent) {
                return $this->error('上级权限错误');
            }

            if($params['platform'] != $parent->platform) {
                return $this->error('上级权限必须同平台');
            }
        }

        $auth = new AdminAuthModel();
        $auth->type = $params['type'];
        $auth->title = $params['title'];
        $auth->platform = $params['platform'];
        $auth->icon = $params['icon'] ?? '';
        $auth->path = $params['path'] ?? '';
        $auth->api = $params['api'] ?? '';
        $auth->sort = $params['sort'] ?? 0;
        $auth->pid = $params['pid'] ?? 0;
        $auth->method = $params['method'] ?? '';
        $auth->name = $params['name'] ?? '';
        $auth->noCache = intval($params['noCache'] ?? 0);
        $auth->save();
        return $this->success();
    }

    public function update(Request $request, int $id){
        $params = $request->all();
        $validator = Validator::make($params, [
            'type' => 'required|in:1,2,3',
            'title' => 'required',
            'platform' => 'required|in:1,2'
        ], [
            'type.required' => '请选择菜单类型',
            'type.in' => '菜单类型错误',
            'title.required' => '请填写标题',
            'platform.required' => '请选择权限平台',
            'platform.in' => '权限平台错误',
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        $method = strtolower($params['method'] ?? '');
        if(!in_array($method, AdminAuthModel::METHOD)) {
            return $this->error('请求方法错误');
        }


        $pid = intval($params['pid'] ?? 0);
        if($pid) {
            $parent = AdminAuthModel::find($pid);
            if(!$parent) {
                return $this->error('上级权限错误');
            }

            if($params['platform'] != $parent->platform) {
                return $this->error('上级权限必须同平台');
            }
        }

        $auth = AdminAuthModel::find($id);
        if(!$auth) {
            return $this->error('参数错误');
        }
        $auth->type = $params['type'];
        $auth->title = $params['title'];
        $auth->platform = $params['platform'];
        $auth->icon = $params['icon'] ?? '';
        $auth->path = $params['path'] ?? '';
        $auth->api = $params['api'] ?? '';
        $auth->sort = $params['sort'] ?? 0;
        $auth->pid = $params['pid'] ?? 0;
        $auth->method = $params['method'] ?? '';
        $auth->name = $params['name'] ?? '';
        $auth->noCache = intval($params['noCache'] ?? 0);
        $auth->save();
        return $this->success();
    }

    public function delete(int $id){
        $e = AdminAuthModel::query()->where('pid', $id)->first();
        if($e->id == 1){
            return $this->error('超级管理员不能删除');
        }

        if($e) {
            return $this->error('先删除子项');
        }
        AdminAuthModel::destroy($id);
        return $this->success();
    }

    public function button_old(Request $request){
        $auth = $request->get('auth');
        $admin = AdminModel::find($auth->id);
        $staff_id = $admin->staff_id;
        $staff = StaffModel::find($staff_id);
        $role_id = $staff->role_id;
         $role = AdminRoleModel::find($role_id);

         if(!$role) {
            return $this->success([]);
         }

        $query = AdminAuthModel::query()
            ->where('platform', AdminAuthModel::ADMIN_PLATFORM)
            ->where('type', AdminAuthModel::BUTTON_TYPE);
        if($role->auth == '*') {
            $buttons = $query->get();
        } else {
            $ids = json_decode($role->auth);
            $buttons = $query->whereIn('id', $ids)->get();
        }
        return $this->success($buttons);
    }

    public function button(Request $request){
        $auth = $request->get('auth');
        $admin = AdminModel::find($auth->id);
//        $staff_id = $admin->staff_id;
//        $staff = StaffModel::find($staff_id);
//        $role_id = $staff->role_id;
//        $role = AdminRoleModel::find($role_id);

        if(!$admin) {
            return $this->success([]);
        }

        $query = AdminAuthModel::query()
            ->where('platform', AdminAuthModel::ADMIN_PLATFORM)
            ->where('type', AdminAuthModel::BUTTON_TYPE);
        if($admin->auth == '*') {
            $buttons = $query->get();
        } else {
            $ids = $admin->auth ? json_decode($admin->auth) : [];
            $buttons = $query->whereIn('id', $ids)->get();
        }
        return $this->success($buttons);
    }


    public function import(Request $request) {
        $auth = $request->get('auth');

        $data = $request->input('data',  []);

        if(!$data) {
            return $this->error('数据为空');
        }

        foreach ($data as &$item){
            if(isset($item['noCache'])){
                $item['noCache'] = $item['noCache'] ? 1 : 0;
            }
        }

        DB::beginTransaction();
        try {
            foreach ($data as $line){
                $auth = new AdminAuthModel();
                foreach ($line as $k => $v){
                    $auth->$k = $v;
                }
                $auth->save();
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }

}
